<?php
// 生成API验证器
$rowKey = '';
$ruleValidate = '';
$saveValidateArr = [];
$saveSceneValidate = '';
$updateSceneValidate = '';
foreach ($field as $key => $val) {
    $prop = $val['prop'];
    if (! empty($val['key']) && $val['key'] == "PRI") {
        $rowKey = $prop;
    } else {
        if ($val['required']) {
            array_push($saveValidateArr, $prop);
            $ruleValidate .= "\n\t\t"."\"{$prop}\" => \"require\",";
        }
    }
    $start    = $key === 0 ? '[' : '';
    $content  = $key === count($field) - 1  ? '"'.$prop.'"' : '"'.$prop.'"'.',';
    $end      = $key === count($field) - 1  ? '],' : '';
    
}
foreach ($saveValidateArr as $key => $val) {
    $start    = $key === 0 ? '[' : '';
    $content  = $key === count($saveValidateArr) - 1  ? '"'.$val.'"' : '"'.$val.'"'.',';
    $end      = $key === count($saveValidateArr) - 1  ? '],' : '';
    $saveSceneValidate   .= $start.$content.$end;
    $updateSceneValidate .= $start.$content.$end;
}
$saveSceneValidate = empty($saveSceneValidate) ? '[""],' : $saveSceneValidate;
$updateSceneValidate = empty($updateSceneValidate) ? '[""],' : $updateSceneValidate;
$apiValidate = '<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\api\validate;

use think\Validate;

class '.$class.' extends Validate
{
    protected $rule = [
        "'.$rowKey.'" => "require|number",
        "page" => "require|number",
        "ids" => "require",'.$ruleValidate.'
    ];
    
    protected $scene = [
        "index"   => ["page"],
        "single"  => ["'.$rowKey.'"],
        "delete"  => ["ids"],
        "save"    => '.$saveSceneValidate.'
        "update"  => '.$updateSceneValidate.'
    ];
}';
// 生成admin验证器
$adminValidate = '<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\validate;

use think\Validate;

class '.$class.' extends Validate
{
    protected $rule = [
        "'.$rowKey.'" => "require|number",
        "page" => "require|number",
        "ids" => "require",'.$ruleValidate.'
    ];
    
    protected $scene = [
        "index"   => ["page"],
        "delete"  => ["ids"],
        "save"    => '.$saveSceneValidate.'
        "update"  => '.$updateSceneValidate.'
    ];
}';
// 生成API控制器
$apiController = '<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\api\controller;

use think\exception\ValidateException;
use app\api\BaseController;
use app\api\validate\\'.$class.' as Validate;
use app\api\model\\'.$class.' as '.$class.'Model;
/**
 * '.$class.'管理
 */
class '.$class.' extends BaseController
{
    /**
     * 显示资源列表
     * 访问：'.$_SERVER['SERVER_NAME'].'/api/'.lcfirst($class).'/index
     */
    public function index()
    {
        if ($this->request->isPost()) {
            try {
                $input = input("post.");
                validate(Validate::class)->scene("index")->check($input);
            } catch ( ValidateException $e ) {
                return json(["status" => "error", "message" => $e->getError()]);
            }
            $count = '.$class.'Model::count();
            $data  = '.$class.'Model::page($input["page"], 10)->select();
            return json(["status" => "success", "message" => "请求成功", "data" => $data, "count" => $count]);
        }
    }
    
    /**
     * 显示资源详情
     */
    public function single()
    {
        if ($this->request->isPost()) {
            try {
                $input = input("post.");
                validate(Validate::class)->scene("single")->check($input);
            } catch ( ValidateException $e ) {
                return json(["status" => "error", "message" => $e->getError()]);
            }
            $data = '.$class.'Model::find($input["id"]);
            return json(["status" => "success", "message" => "请求成功", "data" => $data]);
        }
    }
    
    /**
     * 保存新建的资源
     */
    public function save()
    {
        if ($this->request->isPost()) {
            try {
                $input = input("post.");
                validate(Validate::class)->scene("save")->check($input);
            } catch ( ValidateException $e ) {
                return json(["status" => "error", "message" => $e->getError()]);
            }
            '.$class.'Model::create($input);
            return json(["status" => "success", "message" => "添加成功"]);
        }
    }
    
    /**
     * 保存更新的资源
     */
    public function update()
    {
        if ($this->request->isPost()) {
            try {
                $input = input("post.");
                validate(Validate::class)->scene("update")->check($input);
            } catch ( ValidateException $e ) {
                return json(["status" => "error", "message" => $e->getError()]);
            }
            '.$class.'Model::update($input);
            return json(["status" => "success", "message" => "修改成功"]);
        }
    }
    
    /**
     * 删除指定资源
     */
    public function delete()
    {
        if ($this->request->isPost()) {
            try {
                $input = input("post.");
                validate(Validate::class)->scene("delete")->check($input);
            } catch ( ValidateException $e ) {
                return json(["status" => "error", "message" => $e->getError()]);
            }
            '.$class.'Model::destroy($input["ids"]);
            return json(["status" => "success", "message" => "删除成功"]);
        }
    }
    
    /**
     * 自定义更多方法...
     */
}';

// 生成后台控制器
$adminController = '<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use think\facade\View;
use think\exception\ValidateException;
use app\admin\BaseController;
use app\admin\model\\'.$class.' as '.$class.'Model;
use app\admin\validate\\'.$class.' as Validate;
/**
 * '.$class.'管理
 */
class '.$class.' extends BaseController
{
    /**
     * 显示资源列表
     */
    public function index()
    {
        if ($this->request->isPost()) {
            try {
                $input = input("post.");
                validate(Validate::class)->scene("index")->check($input);
            } catch ( ValidateException $e ) {
                return json(["status" => "error", "message" => $e->getError()]);
            }
            $input = input("post.");
            $count = '.$class.'Model::withSearch(["keyword"], $input)->count();
            $data  = '.$class.'Model::withSearch(["keyword"], $input)->order($input["prop"], $input["order"])->page($input["page"], $input["pageSize"])->select();
            return json(["status" => "success", "message" => "请求成功", "data" => $data, "count" => $count]);
        } else {
            return View::fetch();
        }
    }
    
    /**
     * 保存新建的资源
     */
    public function save()
    {
        if ($this->request->isPost()) {
            try {
                $input = input("post.");
                validate(Validate::class)->scene("save")->check($input);
            } catch ( ValidateException $e ) {
                return json(["status" => "error", "message" => $e->getError()]);
            }
            '.$class.'Model::create($input);
            return json(["status" => "success", "message" => "添加成功"]);
        }
    }
    
    /**
     * 保存更新的资源
     */
    public function update()
    {
        if ($this->request->isPost()) {
            try {
                $input = input("post.");
                validate(Validate::class)->scene("update")->check($input);
            } catch ( ValidateException $e ) {
                return json(["status" => "error", "message" => $e->getError()]);
            }
            '.$class.'Model::update($input);
            return json(["status" => "success", "message" => "修改成功"]);
        }
    }
    
    /**
     * 删除指定资源
     */
    public function delete()
    {
        if ($this->request->isPost()) {
            try {
                $input = input("post.");
                validate(Validate::class)->scene("delete")->check($input);
            } catch ( ValidateException $e ) {
                return json(["status" => "error", "message" => $e->getError()]);
            }
            '.$class.'Model::destroy($input["ids"]);
            return json(["status" => "success", "message" => "删除成功"]);
        }
    }
}';

// 生成API模型
$apiModel = '<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\api\model;

use think\Model;

class '.$class.' extends Model
{
}';

// 生成后台模型
$keywordProp  = [];
$dateProp     = '';
$datePropArr  = [];
$jsonPropArr  = [];
$attrPropArr  = [];
foreach ($field as $key => $val) {
    if ($val['is'] == 'el-date-picker') {
        $dateProp = $val['prop'];
        array_push($datePropArr, $val['prop']);
    }
    if ($val['is'] == 'el-input') {
        array_push($keywordProp, $val['prop']);
    }
    if ($val['is'] == 'el-checkbox-group') {
        array_push($attrPropArr, $val['prop']);
    }
    if ($val['is'] == 'el-select' && $val['multiple'] === true) {
        array_push($attrPropArr, $val['prop']);
    }
    if ($val['is'] == 'el-date-picker') {
        if ($val['type'] === 'daterange' || $val['type'] === 'datetimerange') {
            array_push($attrPropArr, $val['prop']);
        }
    }
    if ($val['is'] == 'el-file-list-select' || $val['is'] == 'el-link-select' || $val['is'] == 'el-parameter') {
        array_push($jsonPropArr, $val['prop']);
    }
}
$jsonProp = '';
foreach ($jsonPropArr as $key => $val) {
    $start    = $key === 0 ? '[' : '';
    $content  = $key === count($jsonPropArr) - 1  ? '"'.$val.'"' : '"'.$val.'"'.',';
    $end      = $key === count($jsonPropArr) - 1  ? ']' : '';
    $jsonProp.= $start.$content.$end;
}
$jsonProp = empty($jsonProp) ? "[]" : $jsonProp;
$attrProp = '';
foreach ($attrPropArr as $key => $val) {
    $name = ucfirst(str_replace(' ','',lcfirst(ucwords(str_replace('_', ' ', $val)))));
    $str  = $key == 0 ? "" : "\n\n\t"; 
    $attrProp .= $str.'public function get'.$name.'Attr($value, $array)
    {
        return $value ? explode(",", $value) : [];
    }
    
    public function set'.$name.'Attr($value, $array)
    {
        return implode(",", $value);
    }';
}
$attrDate = '';
foreach ($datePropArr as $key => $val) {
    $name = ucfirst(str_replace(' ','',lcfirst(ucwords(str_replace('_', ' ', $val)))));
    $str  = $key == 0 && $attrProp == "" ? "\n\n" : "\n\n\t"; 
    $attrDate .= $str.'public function set'.$name.'Attr($value, $array)
    {
        return empty($value) ? date("Y-m-d H:i:s") : $value;
    }';
}
$admminModel = '<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\model;

use think\Model;

class '.$class.' extends Model
{
    // 设置json类型字段
    protected $json = '.$jsonProp.';

    // 设置JSON数据返回数组
    protected $jsonAssoc = true;
    
    // 搜索器
    public function searchKeywordAttr($query, $value)
    {
    	if (! empty($value)) {
	        $query->where("'.implode('|', $keywordProp).'","like", "%" . $value . "%");
	    }
    }
    
    public function searchDateAttr($query, $value, $array)
    {
        if (! empty($value)) { 
            $query->whereBetweenTime("'.$dateProp.'", $value[0], $value[1]);
        }
    }
    
    // 修改器、获取器
    '.$attrProp.$attrDate.'
}';
// 生成后台视图
$viewFieldStr = "[";
foreach ($field as $key => $val) {
    $viewFieldStr .= "\n\t\t\t\t\t{";
    $viewFieldStr .= "\n\t\t\t\t\t\tprop: '".$val['prop']."',";
    $viewFieldStr .= "\n\t\t\t\t\t\tlabel: '".$val['label']."',"; 
    // 表格
    if (! $val['tableShow']) {
    $viewFieldStr .= "\n\t\t\t\t\t\ttable: false,";
    } else {
    $viewFieldStr .= "\n\t\t\t\t\t\ttable: {";
    if ($val['is'] == 'el-file-list-select') {
    $viewFieldStr .= "\n\t\t\t\t\t\t\tis: 'el-images',";
    }
    if ($val['is'] == 'el-file-select') {
    $viewFieldStr .= "\n\t\t\t\t\t\t\tis: 'el-image',";
    }
    if ($val['tableSort']) {
    $viewFieldStr .= "\n\t\t\t\t\t\t\tsort: true,";
    }
    if (! empty($val['tableBind'])) {
    $viewFieldStr .= "\n\t\t\t\t\t\t\tbind: ".json_encode($val['tableBind'],JSON_UNESCAPED_UNICODE).",";
    }
    $viewFieldStr .= "\n\t\t\t\t\t\t},";
    }
    // 表单
    if (! $val['formShow']) {
    $viewFieldStr .= "\n\t\t\t\t\t\tform: false";
    } else {
    $viewFieldStr .= "\n\t\t\t\t\t\tform: {";
    $viewFieldStr .= "\n\t\t\t\t\t\t\tis: '".$val['is']."',";
    if ($val['placeholder'] !== '' && $val['is'] == 'el-input' || $val['is'] == 'el-editor' || $val['is'] == 'el-select') {
    $viewFieldStr .= "\n\t\t\t\t\t\t\tplaceholder: '".$val['placeholder']."',";
    }
    if ($val['tips'] !== '') {
    $viewFieldStr .= "\n\t\t\t\t\t\t\ttips: '".$val['tips']."',";    
    }
    if ($val['default'] !== '') {
    if (is_array($val['default'])) {
        $default = json_encode($val['default'],JSON_UNESCAPED_UNICODE);
    } else {
        $default = is_numeric($val['default']) ? intval($val['default']) : '\''.$val['default'].'\'';
    }
    $viewFieldStr .= "\n\t\t\t\t\t\t\tdefault: " . $default . ",";    
    }
    if ($val['pattern'] !== '' || $val['required']) {
    $viewFieldStr .= "\n\t\t\t\t\t\t\trules: [";
    if ($val['required']) {
    $viewFieldStr .= "\n\t\t\t\t\t\t\t\t{required: true, message: '请输入'},";
    }
    if ($val['pattern'] !== '' && $val['is'] == 'el-input') {
    $viewFieldStr .= "\n\t\t\t\t\t\t\t\t{pattern: ".$val['pattern'].",message: '格式错误'},";    
    }
    $viewFieldStr .= "\n\t\t\t\t\t\t\t],";
    }
    if ($val['disabled']) {
    $viewFieldStr .= "\n\t\t\t\t\t\t\tdisabled: true,";
    }
    if ($val['colMd'] !== '' && $val['colMd'] != $input['form_col_md']) {
    $viewFieldStr .= "\n\t\t\t\t\t\t\tcolMd: ".$val['colMd'].",";
    }
    if ($val['is'] == 'el-radio-group' || $val['is'] == 'el-checkbox-group' || $val['is'] == 'el-select') {
    $viewFieldStr .= "\n\t\t\t\t\t\t\tchild: {";
    foreach ($val['child'] as $k => $v) {
        if ($val['is'] == 'el-radio-group' || $val['is'] == 'el-select') {
            if (is_numeric($v['value'])) {
                $val['child'][$k]['value'] = $val['multiple'] && $val['is'] == 'el-select' ? $v['value'] : intval($v['value']);
            }
        }
    }
    $viewFieldStr .= "\n\t\t\t\t\t\t\t\tvalue: ".json_encode($val['child'],JSON_UNESCAPED_UNICODE).",";
    $viewFieldStr .= "\n\t\t\t\t\t\t\t\tprops: {label: 'title', value: 'value'}";
    $viewFieldStr .= "\n\t\t\t\t\t\t\t},";
    }
    if ($val['type'] !== '' && $val['is'] == 'el-input' || $val['is'] == 'el-file-select' || $val['is'] == 'el-file-list-select' || $val['is'] == 'el-date-picker') {
    $viewFieldStr .= "\n\t\t\t\t\t\t\ttype: '".$val['type']."',";
    if ($val['type'] == 'date' || $val['type'] == 'daterange') {
    $viewFieldStr .= "\n\t\t\t\t\t\t\tformat: 'yyyy-MM-dd',";
    $viewFieldStr .= "\n\t\t\t\t\t\t\tvalueFormat: 'yyyy-MM-dd',";
    }
    if ($val['type'] == 'datetime' || $val['type'] == 'datetimerange') {
    $viewFieldStr .= "\n\t\t\t\t\t\t\tformat: 'yyyy-MM-dd HH:mm:ss',";
    $viewFieldStr .= "\n\t\t\t\t\t\t\tvalueFormat: 'yyyy-MM-dd HH:mm:ss',";
    }
    }
    if ($val['is'] == 'el-select') {
    $filterable = $val['filterable'] ? 'filterable: true' : 'filterable: false';
    $multiple   = $val['multiple'] ? 'multiple: true' :' multiple: false';
    $viewFieldStr .= "\n\t\t\t\t\t\t\t".$filterable.",";
    $viewFieldStr .= "\n\t\t\t\t\t\t\t".$multiple.",";
    }
    $viewFieldStr .= "\n\t\t\t\t\t\t}";
    }
    $viewFieldStr .= "\n\t\t\t\t\t},";
}
$viewFieldStr .= "\n\t\t\t\t]";
$adminView  = '{include file="common/header"}';
$adminView .= "\n".'<div id="app" v-cloak>';
$adminView .= "\n\t".'<el-curd';
$adminView .= "\n\t\t".':field="field"';
if ($rowKey != 'id') {
$adminView .= "\n\t\t".'row-key="'.$rowKey.'"';
}
if ($input['form_label_width'] != 100) {
$adminView .= "\n\t\t".':form-label-width="'.$input['form_label_width'].'px"';
}
if ($input['form_col_md'] != 24) {
$adminView .= "\n\t\t".':form-col-md="'.$input['form_col_md'].'"';
}
if ($input['table_export'] == 0) {
$adminView .= "\n\t\t".':table-export="false"';
}
if ($input['table_sort'] !== '') {
$adminView .= "\n\t\t".':table-sort="{prop: \''.$input['table_sort'].'\', order: \'desc\'}"';
}
if ($input['search_keyword'] == 0) {
$adminView .= "\n\t\t".':search-keyword="false"';
}
if ($input['search_date'] == 0) {
$adminView .= "\n\t\t".':search-date="false"';
}
if ($input['table_tree'] == 1) {
$adminView .= "\n\t\ttable-tree";
}
$adminView .= ">";
$adminView .= "\n\t".'</el-curd>';
$adminView .= "\n".'</div>';
$adminView .= "\n".'<script>';
$adminView .= "\n\t".'new Vue({';
$adminView .= "\n\t\t".'el: "#app",';
$adminView .= "\n\t\t".'data() {';
$adminView .= "\n\t\t\t".'return {';
$adminView .= "\n\t\t\t\t".'field: '.$viewFieldStr.',';
$adminView .= "\n\t\t\t".'}';
$adminView .= "\n\t\t".'},';
$adminView .= "\n\t".'})';
$adminView .= "\n".'</script>';
$adminView .= "\n".'{include file="common/footer"}';